import React from 'react';
import {
  Card,
  Button,
  Row,
  Col,
  Icon,
  Tabs,
  Table,
  Radio,
  DatePicker,
  Tooltip,
  Menu,
  Dropdown,
  Input,
  Divider,
  message,
  Upload,
  Modal,
  List,
  Switch,
  notification,
  Avatar,
  Popconfirm,
  Cascader,
  InputNumber
} from 'antd';

import { StyleSheet, css } from 'aphrodite';

import { swap } from 'react-magic';
import styles from './vip.less';
import moment from 'moment/moment';
import { getValueWithLocalStorage } from '@/utils/authority';

const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const { TextArea } = Input;
const { MonthPicker, RangePicker } = DatePicker;
const { Meta } = Card;

import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';

const styles_animation = StyleSheet.create({
  magic: {
    animationName: swap,
    animationDuration: '1s',
  },
});

import { connect } from 'dva';

const namespace = 'vip';

const userInfo = getValueWithLocalStorage('userinfo');

import router from 'umi/router';
import NumberInfo from "../../components/NumberInfo";

const mapStateToProps = state => {
  const ret = state[namespace].ret;
  const isLoading = state[namespace].isLoading;

  return {
    ret,
    isLoading,
  };
};

const mapDispatchToProps = dispatch => {
  return {
    addServicesTempalte: (para, _owner, callback) => {
      const action = {
        type: `${namespace}/addServicesTempalte`,
        payload: {
          ...para,
          callback: callback,
          owner: _owner,
        },
      };
      dispatch(action);
    },

    getShopServices: (_owner, callback) => {
      const action = {
        type: `${namespace}/getShopServices`,
        payload: {
          callback: callback,
          owner: _owner,
        },
      };
      dispatch(action);
    },

    editServicesTemplate: (para, _owner, callback) => {
      const action = {
        type: `${namespace}/editServicesTemplate`,
        payload: {
          ...para,
          callback: callback,
          owner: _owner,
        },
      };
      dispatch(action);
    },

    addServicesTempalteItem: (para, _owner, callback) => {
      const action = {
        type: `${namespace}/addServicesTempalteItem`,
        payload: {
          ...para,
          callback: callback,
          owner: _owner,
        },
      };
      dispatch(action);
    },


  };
};
@connect(
  mapStateToProps,
  mapDispatchToProps
)
export default class AddServiceTemplate extends React.Component {
  constructor(props) {
    super(props);
    var isNew =  this.props.location.query._id == undefined
    this.state = {
      _id: isNew ? '' : this.props.location.query._id,
      title:isNew ? '' : this.props.location.query.name,
      mask:isNew ? '' : this.props.location.query.mark,
      circle:isNew ? '0' : this.props.location.query.circle,
      price:isNew ? '0' : this.props.location.query.price,
      isforever:isNew ? false : this.props.location.query.isforever,
      isNew: isNew,
      value:'',
      servicesItmes:[],
      selectedOptions:[],
      templateItems:isNew ? [] : this.props.location.query.serviceitems,
      num:0,
      shopTel:this.props.location.query.shop  == undefined ? userInfo.tel:this.props.location.query.shop,

    };
  }

  /*****************************model's callback********************************/

  addCallback = res => {
    if (res.code == 0) {
      message.error(res.msg);
    } else {
      message.success(res.msg);
      router.push('/vip/servicesTemplate');
    }
  };

  componentDidMount = () => {

    this.props.getShopServices(this.state.shopTel,res=>{
       this.setState({servicesItmes:res})
    })
  };

  render() {
    var that = this;
    const NUM_TITLE = 20;
    const userInfo = getValueWithLocalStorage('userinfo');
    return (
      <Card title={that.state.isNew ? '新增服务套餐模版' : '编辑服务套餐模版'} bordered={false}>
        <Row className={styles.row} gutter={10}>
          <Col span={8}>
            <span className={styles.tipLab}>模版标题</span>
          </Col>
          <Col span={16}>
            <Input
              value={that.state.title}
              onChange={e => {
                if (e.target.value.length > NUM_TITLE) {
                  message.warning('超出字数限制');
                  return;
                }
                that.setState({ title: e.target.value });
              }}
            />
          </Col>
        </Row>
        <Row className={styles.row} gutter={10}>
          <Col span={8}>
            <span className={styles.tipLab}>模版简介</span>
          </Col>
          <Col span={16}>
            <Input
              value={that.state.mask}
              onChange={e => {
                that.setState({ mask: e.target.value });
              }}
            />
          </Col>
        </Row>
        <Row className={styles.row} gutter={10}>
          <Col span={8}>
            <span className={styles.tipLab}>有效期(天)</span>
          </Col>
          <Col span={16}>
            <InputNumber
              value={that.state.circle}
              onChange={e => {
                that.setState({ circle: e});
              }}
            />
          </Col>
        </Row>
        <Row className={styles.row} gutter={10}>
          <Col span={8}>
            <span className={styles.tipLab}>套餐价格(元)</span>
          </Col>
          <Col span={16}>
            <InputNumber
              value={that.state.price}
              onChange={e => {
                that.setState({ price: e});
              }}
            />
          </Col>
        </Row>
        <Row className={styles.row} gutter={10}>
          <Col span={8}>
            <span className={styles.tipLab}>长期套餐</span>
          </Col>
          <Col span={16}>
            <Switch value={that.state.isforever} onChange={value=>{
                that.setState({isforever:value})
            }} />
          </Col>
        </Row>
        <Row className={styles.row} gutter={10}>
          <Col span={8}>
            <span className={styles.tipLab}>套餐项目</span>
          </Col>
          <Col className={styles.edit2} span={16}>
              <Row className={styles.row2} gutter={10}>
                <Col span={24}>
                  <Cascader
                    className={styles.subtypeselect}
                    size={"small"}
                    placeholder={"请选择服务项目"}
                    options={that.state.servicesItmes}
                    fieldNames={{label:'name',value:'name',children:'subtype'}}
                    onChange={(value, selectedOptions)=>{
                      console.log(value)
                      that.setState({selectedOptions:selectedOptions})
                    }} />
                </Col>
              </Row>
              <Row className={styles.row2} gutter={10}>
                <Col span={24}>
                  <InputNumber
                    min={0}
                    max={100}
                    size={"small"}
                    className={styles.num}
                    placeholder={"次数"}
                    onChange={e => {
                      that.setState({ num: e});
                    }}
                  />
                </Col>
              </Row>
              <Row className={styles.row2} gutter={10}>
              <Col span={24}>
                <Button
                  type="primary"
                  block
                  onClick={() => {
                    if(that.state.selectedOptions.length < 2){
                      message.error("服务项目未添加")
                      return
                    }
                    if(that.state.num == 0){
                      message.error("服务次数未编辑")
                      return
                    }

                    that.props.addServicesTempalteItem({
                      num:that.state.num,
                      name:that.state.selectedOptions[1].name,
                      serviceitem:that.state.selectedOptions[1]._id
                      }, that.state.shopTel, res=>{
                          if(res.code == 1) {
                             var arr = that.state.templateItems
                             arr.push(res.ret)
                            that.setState({templateItems:arr})
                          }
                      }
                    )
                  }}
                >
                  添加
                </Button>
              </Col>
            </Row>
          </Col>

        </Row>

        <Row className={styles.row} gutter={10}>
          <Col span={8}>
            <span className={styles.tipLab}>服务项目</span>
          </Col>
          <Col span={16}>
            <List
              bordered={true}
              dataSource={that.state.templateItems}
              renderItem={(item) => (
                <List.Item >
                  <span className={styles.itmeCellTextStyle}>{item.name+" x"+item.num}</span>

                  <Popconfirm
                    title="确认删除此服务?"
                    onConfirm={() => {
                      const index = that.state.templateItems.indexOf(item);
                      const _arr = that.state.templateItems.splice(index, 1);
                      that.setState({ templateItems: that.state.templateItems });
                    }}
                    okText="确认"
                    cancelText="取消"
                  >
                  <Button
                    size={"small"}
                    className={styles.delBtn}
                  >
                  x
                  </Button>
                  </Popconfirm>
                </List.Item>
              )}
            />
          </Col>
        </Row>

        <Row className={styles.row} gutter={48}>
          <Col offset={3} span={18}>
            <Button
              type="primary"
              block
              onClick={() => {

                if(that.state.title.length == 0){
                  message.error('标题不能为空!')
                  return
                }
                if(that.state.mask.length == 0){
                  message.error('描述不能为空!')
                  return
                }

                var arr = that.state.templateItems.map(item=>{
                  return item._id
                })

                if (that.state.isNew) {

                  that.props.addServicesTempalte(
                    {
                      name:that.state.title,
                      price:that.state.price,
                      mark:that.state.mask,
                      circle:that.state.circle,
                      isforever:that.state.isforever,
                      serviceitems:arr,
                    },
                    that.state.shopTel, res=>{
                    if (res.code == 0) {
                      message.error(res.msg);
                    } else {
                      message.success(res.msg);
                      router.goBack()
                      // router.push(userInfo == null ?'/vip-client/servicesTemplate':  '/vip/servicesTemplate');
                    }
                  });
                } else {
                  that.props.editServicesTemplate(
                    {
                      id:that.state._id,
                      name:that.state.title,
                      price:that.state.price,
                      mark:that.state.mask,
                      circle:that.state.circle,
                      isforever:that.state.isforever,
                      serviceitems:arr,},
                    that.state.shopTel,
                    res=>{
                      if (res.code == 0) {
                        message.error(res.msg);
                      } else {
                        message.success(res.msg);
                        router.goBack()
                        // router.push(userInfo == null ?'/vip-client/servicesTemplate':  '/vip/servicesTemplate');
                      }
                    }
                  );
                }
              }}
            >
              {that.state.isNew ? '确认添加' : '确认编辑'}
            </Button>
          </Col>
        </Row>
      </Card>
    );
  }
}
